import { ComponentClass } from 'react'
import Taro, { Component, Config } from '@tarojs/taro'
import { View, Image, Button } from '@tarojs/components'
import { connect } from '@tarojs/redux'

import bannerImg from '../../asset/images/step-apply-two/banner-step-2.jpg'
import { noConsole } from '../../config'
import ApplyFormItem from '../../model/apply-form'
import ApplyForm from '../../components/apply-form'
import AgreeProtocolRadio from '../../components/agree-protocol-radio'

import './index.scss'
import { Utils } from '../../utils/utils';
import ProductUtils from '../../utils/product'
import { User as UserUtils } from '../../utils/user'


const utils = new Utils()
const productUtils = new ProductUtils()
const userUtils = new UserUtils()

// #region 书写注意
// 
// 目前 typescript 版本还无法在装饰器模式下将 Props 注入到 Taro.Component 中的 props 属性
// 需要显示声明 connect 的参数类型并通过 interface 的方式指定 Taro.Component 子类的 props
// 这样才能完成类型检查和 IDE 的自动提示
// 使用函数模式则无此限制
// ref: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/20796
//
// #endregion

type PageStateProps = {
  form: ApplyFormItem[]
  formValue: any,
  stepOneFormValue: any,    // 第一步提交的表单值对象
  isAgreeProtocol: boolean, // 是否同意协议
}

type PageDispatchProps = {
  dispatchSave: (param: any) => void,
}

type PageOwnProps = {}

type PageState = {}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface SetpApplyTwo {
  props: IProps;
  state: PageState;
}

@connect(({ stepApplyOne, stepApplyTwo, common, loading }) => ({
 stepOneFormValue: stepApplyOne.formValue,
  ...stepApplyTwo,
  ...common,
  ...loading,
}), (dispatch) => ({
  dispatchSave(param: any) {
    dispatch({
      type: 'stepApplyTwo/save',
      payload: param
    })
  },
}))
class SetpApplyTwo extends Component {

  constructor(props) {
    super(props);
  }

  componentWillReceiveProps(nextProps) { }

  componentWillMount() { }

  componentDidMount() { 
    // 初始化表单
    this.initForm()
  }

  componentWillUnmount() { 

  }

  componentDidShow() { }

  componentDidHide() { }

  render() {
    const { form, formValue } = this.props
    // console.log('state.searchOption = ', this.state.searchOption)
    // console.log('searchOption = ', searchOption)

    return (
      <View className='step-apply-two-container'>
        {/* <!-- 头部宣传栏分块 --> */}
        <View className="product-banner">
          <Image src={bannerImg}></Image>
        </View>
        <View className="apply-info-box">
          <ApplyForm form={form} formValue={formValue} dispatchType={'stepApplyTwo/updateFormItem'}/>
        </View>

        {/* <!-- 底部按钮 --> */}
        <View className="bottom-box">
          <View className="bottom-radio-box">
            <AgreeProtocolRadio isAgreeProtocol={ this.props.isAgreeProtocol } dispatchType={'stepApplyTwo/save'}/>
          </View>
          <Button onClick={this.submit}>下一步</Button>
        </View>
      </View>
    )
  }

  /**
   * 根据产品对象初始化表单数据
   */
  initForm() {
    const { formValue, stepOneFormValue } = this.props
    const formCopy = Object.assign({}, formValue)

    // 加载缓存
    const formCache = productUtils.getApplyFormFromStorage()
    if (formCache) {
      Object.assign(formCopy, formCache)
    }

    // // 从服务器请求信用数据
    // applyModel.getUserCredit().then(res => {
    //   // 用信用数据填写表单
    //   const credit = res.data
    //   Object.assign(form, credit)

    //   this.setData({
    //     form
    //   })
    // }, error => {
    //   console.error('getUserCredit has error ', error)
    //   this.setData({
    //     form
    //   })
    // })
    
    this.props.dispatchSave({
      formValue: formCopy
    })
  }

  /**
   * 提交申请表单的方法
   */
  submit = () => {

    if (!this.props.isAgreeProtocol) {
      Taro.showToast({
        title: '请同意《壹融时代服务条款》',
        icon: 'none',
      })
      return
    }

    const validatorResult = utils.formValidation(this.props.form, this.props.formValue)
    if (!validatorResult.isValidate) {
      Taro.showToast({
        title: validatorResult.msg,
        icon: 'none',
      })
      return
    }

    // 合并两个表单
    const combineForm = Object.assign(this.props.formValue, this.props.stepOneFormValue)

    // 保存表单信息到local storage
    productUtils.saveApplyFormToStorage(combineForm)

    const { formValue } = this.props
    Taro.navigateTo({
      url: `/pages/stepApplyMatch/index?deposit=${formValue.loan_limit}&time_limit=${formValue.loan_date_limit}`
    })
  }

}

// #region 导出注意
//
// 经过上面的声明后需要将导出的 Taro.Component 子类修改为子类本身的 props 属性
// 这样在使用这个子类时 Ts 才不会提示缺少 JSX 类型参数错误
//
// #endregion

export default SetpApplyTwo as ComponentClass<PageOwnProps, PageState>
